package smcms.service.sso.utils;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class IOUtils {

    public static Logger logger = LoggerFactory.getLogger(IOUtils.class);

    public static void exportExcel(List<?> mapList, String exportFileName, HttpServletResponse response, Class clazz, List<String> rowName){
        SXSSFWorkbook wb = null;
        try {
            wb = new SXSSFWorkbook();
            SXSSFSheet sheet = wb.createSheet();
            Row titleRow = sheet.createRow((short) 0);
            int multiple = 0;
            Field[] declaredFields = clazz.getDeclaredFields();
            for (int i = 0, size = rowName.size(); i < size; i++) {
                Cell cell = titleRow.createCell(i);
                multiple = rowName.get(i) == null ? 0 : rowName.get(i).length();
                sheet.setColumnWidth(i, multiple * 800);
                cell.setCellValue(rowName.get(i));
            }
            if (CollectionUtils.isEmpty(mapList)) {
                return;
            }
            for (int i = 0, size = mapList.size(); i < size; i++) {
                Row row = sheet.createRow(i + 1);
                for (int j = 0, length = clazz.getDeclaredFields().length; j < length; j++) {
                    Method method = clazz.getDeclaredMethod("get" + captureName(declaredFields[j].getName()));
                    Object invokeValue = method.invoke(mapList.get(i));
                    String res = ObjectUtils.isEmpty(invokeValue) ? "" : invokeValue.toString();
                    row.createCell(j).setCellValue(res);
                }
            }
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(exportFileName, "utf-8"));
            OutputStream outputStream = response.getOutputStream();
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();
            wb.dispose();
        }
        catch (IOException ex) {
            logger.info("导出IO异常");
        }
        catch (Exception e) {
            logger.info("导出异常");
        }
        finally {
            logger.info("流关闭异常");
        }
    }
    private List<Object> importExcel(MultipartFile file, Class clazz) throws Exception {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("文件不能为空！");
        }
        Workbook workbook = null;
        List<Object> list = new ArrayList<>();
        //查询组织
        try {
            //获取Excel
            workbook = WorkbookFactory.create(file.getInputStream());
            //便利所以sheet
            for (int numShett = 0; numShett < workbook.getNumberOfSheets(); numShett++) {
                Sheet sheet = workbook.getSheetAt(numShett);
                if (ObjectUtils.isEmpty(sheet)) {
                    continue;
                }
                //循环便利所以行
                for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
                    //实例化导入对象
                    Object newInstance = clazz.newInstance();
                    //获取行
                    Row row = sheet.getRow(rowNum);
                    //如果是空行跳过
                    if (ObjectUtils.isEmpty(row) || isRowEmpty(row)) {
                        continue;
                    }
                    //拿到所以字段
                    Field[] fields = clazz.getDeclaredFields();
                    int cellIndex = 0;
                    //便利所有字段
                    for (int i = 0; i < fields.length; i++) {
                        Method method = clazz.getDeclaredMethod("set" + captureName(fields[i].getName()), fields[i].getType());
                        if (row.getCell(i) != null) {
                            String cellValue = row.getCell(i).getStringCellValue();
                            method.invoke(newInstance, cellValue);
                        }
                    }
                    //返回list
                    list.add(newInstance);
                }
            }
        }
        catch (Exception e) {
            throw new Exception(e.getMessage());
        }
        return list;
    }
    //过滤空行
    private  boolean isRowEmpty(Row row) {
        for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {
            Cell cell = row.getCell(c);
            if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK) {
                return false;
            }
        }
        return true;
    }
    //首字母大写
    private static String captureName(String name) {
        name = name.substring(0, 1).toUpperCase() + name.substring(1);
        return  name;
    }
}
